package com.mioto.ld.module.alert.statistic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mioto.ld.module.device.dao.DeviceAlertLogDao;
import com.mioto.ld.module.device.model.DeviceAlertCounterStatisticsVO;
import com.mioto.ld.module.device.model.DeviceAlertLevelStatisticsVO;
import com.mioto.ld.module.device.model.DeviceAlertStatisticsVO;
import com.mioto.ld.module.statistics.StatisticsUtil;
import com.mioto.ld.utils.BaseUtil;
import com.mioto.ld.utils.SpringBeanUtil;

import java.util.*;

/**
 * @author mioto-qinxj
 * @date 2024/6/15
 * @desc
 */
public abstract class AbstractDeviceAlertStatistics {

    /**
     * 分组数量
     */
    protected int index;
    protected Date startDate;
    protected Date endDate;
    private DeviceAlertLogDao deviceAlertLogDao;

    protected AbstractDeviceAlertStatistics(){

    }

    public DeviceAlertStatisticsVO statistics(String startTime, String endTime, int type){
        calculateDate(startTime,endTime);
        DeviceAlertStatisticsVO deviceAlertStatisticsVO = new DeviceAlertStatisticsVO();
        deviceAlertStatisticsVO.setCounterStatisticsVOS(counterStatistics(type));
        deviceAlertStatisticsVO.setLevelStatisticsVOS(levelStatistics());
        return deviceAlertStatisticsVO;
    }

    private List<DeviceAlertCounterStatisticsVO> counterStatistics(int type){
        List<DeviceAlertCounterStatisticsVO> counterStatistics = getDeviceAlertLogDao().counterStatistics(startDate,endDate,type, BaseUtil.buildUserFilterCondition());
        if (CollUtil.isNotEmpty(counterStatistics)){
            counterStatistics = (List<DeviceAlertCounterStatisticsVO>) StatisticsUtil.reBuild(counterStatistics,genDeviceAlertCounterStatisticsVO(),index);
        }
        return counterStatistics;
    }

    private List<DeviceAlertLevelStatisticsVO> levelStatistics(){
        return getDeviceAlertLogDao().levelStatistics(startDate,endDate,BaseUtil.buildUserFilterCondition());
    }

    /**
     * 创建一个长度为index的规律数组
     * @return
     */
    protected abstract DeviceAlertCounterStatisticsVO[] genDeviceAlertCounterStatisticsVO();

    /**
     * 计算搜索时间
     * @param startTime
     * @param endTime
     */
    protected abstract void calculateDate(String startTime, String endTime);

    protected abstract String buildTimeStr(int index);

    private DeviceAlertLogDao getDeviceAlertLogDao(){
        if (ObjectUtil.isNull(deviceAlertLogDao)){
            deviceAlertLogDao = SpringBeanUtil.getBean(DeviceAlertLogDao.class);
        }
        return deviceAlertLogDao;
    }
}
